import time
import random
import math
import Util

def wander( mobile ):
    """
    Makes a mobile wander aimlessly about the playing surface.
    """
    now = time.time()
    if now - mobile.behavior_timer > 1:
        mobile.behavior_timer = now
        axis = random.randrange(0,2) # pick either 0 or 1
        velocity = random.randrange(-mobile.acceleration,
            2*mobile.acceleration,mobile.acceleration) # + or - accel
        mobile.set_velocity(axis,velocity)
    elif now - mobile.behavior_timer > random.random() + 0.3:
        mobile.set_velocity(0,0)
        mobile.set_velocity(1,0)
        
        
def follow( target, until=2.5, accuracy=32  ):
    """
    Makes a mobile follow a target.
    """
    stop_distance = (target.sprite_width * until) ** 2
    def func( mobile ):
        now = time.time()
        dist = Util.distance_squared( mobile.position, target.position )
        if dist <= stop_distance:
            mobile.set_velocity(0,0)
            mobile.set_velocity(1,0)
        elif dist > stop_distance and now - mobile.behavior_timer > 0.5:
            mobile.behavior_timer = now
            m_x,m_y = mobile.position
            t_x,t_y = target.position
            if m_x > t_x + accuracy:
                mobile.set_velocity(0,-mobile.acceleration)
            elif m_x < t_x - accuracy:
                mobile.set_velocity(0,mobile.acceleration)
            else:
                mobile.set_velocity(0,0)
            
            if m_y > t_y + accuracy:
                mobile.set_velocity(1,-mobile.acceleration)
            elif m_y < t_y - accuracy:
                mobile.set_velocity(1,mobile.acceleration)
            else:
                mobile.set_velocity(1,0)
    return func
            
